<template>
  <div class="person card">
    <h3 class="title">个微加好友设置</h3>
    <el-form :model="addForm" :rules="addRules" ref="addFormRef">
      <p class="step-name">第一步：设置验证语</p>

      <div class="step">
        <el-form-item prop="verifyMessage">
          <el-input v-model="addForm.verifyMessage" type="textarea" :rows="5"></el-input>
        </el-form-item>
      </div>

      <p class="step-name">第二步：设置时间间隔</p>

      <div class="step">
        <div class="time-range">
          <el-form-item prop="time">
            <el-time-picker
              v-model="addForm.time"
              @change="changeTime"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>
        </div>
        <div class="time-around">
          <el-form-item prop="space">
            <div v-if="aroundTime" class="tip">
              每隔 <el-input-number v-model="addForm.space" :max="aroundTime" :min="0"></el-input-number> 秒执行一次添加任务
            </div>
          </el-form-item>
        </div>
        <p class="step-name">第三步：上传资料表格</p>

        <div class="step">
          <div class="tips">{{ excelData.name }}</div>
          <div class="btns">
            <ImportExcel style="margin-left: 12px" @success="getExcel" />
          </div>
        </div>

        <p class="step-name">第四步：选择执行账号</p>

        <div class="step">
          <div class="checkbox">
            <el-form-item prop="accountList">
              <el-checkbox-group v-model="addForm.accountList">
                <el-checkbox
                  :class="item.accountType === '企微' ? 'green-text' : ''"
                  :label="item.accountName"
                  :value="item.accountId"
                  v-for="item of accountData.slice(0, 5)"
                  :key="item.accountId"
                />
              </el-checkbox-group>
            </el-form-item>
          </div>
          <div v-if="accountData.length > 5" class="more-btn">
            ......
            <el-button @click="toMore">选择更多</el-button>
          </div>
          <div v-if="addForm.accountList.length" class="account-info">
            已选择 <span>{{ addForm.accountList.length }}</span> 个账号
          </div>

          <div class="tips" v-if="detailList.length">{{ task }}</div>
          <div class="btns">
            <el-button type="success" :icon="DocumentAdd" @click="startAdd">开始添加</el-button>
            <el-button type="primary" :icon="VideoPause" @click="pauseAdd" :disabled="!isPause">暂停添加</el-button>
            <el-button type="danger" :icon="Close" @click="stopAdd" :disabled="!isPause">停止添加</el-button>
            <el-button type="primary" :icon="Refresh" @click="getDetail">查询任务</el-button>
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { DocumentAdd, VideoPause, Close, Refresh } from "@element-plus/icons-vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { useRouter } from "vue-router";
import { getAccountListApi, getTaskDetailApi, pauseTaskApi, startTaskApi, stopTaskApi } from "@/api/modules/business";
import { AccountList, DetailList } from "@/api/interface";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/modules/user";

const router = useRouter();
const userStore = useUserStore();
const initForm = () => {
  return {
    time: [],
    startTime: "",
    endTime: "",
    space: 0,
    verifyMessage: "",
    accountList: []
  };
};
const addForm = ref(initForm());
const addRules = {
  verifyMessage: { required: true, message: "请输入验证语", trigger: "blur" },
  time: { required: true, message: "请选择时间", trigger: "blur" },
  space: { required: true, message: "请输入间隔时间", trigger: "blur" },
  accountList: { required: true, message: "请选择账号", trigger: "blur" }
};
const addFormRef = ref<any>(null);
const aroundTime = ref(0);
const accountData = ref<AccountList[]>([]);
const detailList = ref<DetailList[]>([]);
const task = computed(() => detailList.value[0].message || "");
const isPause = computed(() => detailList.value.map(item => item.state === "MM_TASK_RUN").length > 0);
const excelData = ref({ url: "", name: "" });

function changeTime(val: Date[] | null) {
  addForm.value.space = 0;
  if (val) {
    const time = new Date(val[1]).getTime() - new Date(val[0]).getTime();
    aroundTime.value = time / 1000;
    addForm.value.startTime = dayjs(val[0]).format("HH:mm:ss");
    addForm.value.endTime = dayjs(val[1]).format("HH:mm:ss");
  } else {
    aroundTime.value = 0;
    addForm.value.startTime = "";
    addForm.value.endTime = "";
  }
}

function getExcel(data: { url: string; name: string }) {
  excelData.value = data;
}

function toMore() {
  userStore.setTaskInfo(addForm.value);
  router.push({ name: "selectAccount", query: { type: "person" } });
}

function startAdd() {
  addFormRef.value.validate((valid: boolean) => {
    if (valid) {
      ElMessageBox.confirm("确认开始添加任务？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const data = await startTaskApi(addForm.value);
        console.log("data", data);
        if (!data.result) return ElMessage.error(data.message);
        ElMessage.success(data.message || "操作成功");
        addForm.value = initForm();
      });
    }
  });
}

function pauseAdd() {
  ElMessageBox.confirm("确认暂停添加任务？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const data = await pauseTaskApi();
    console.log("data", data);
    if (data.result) return ElMessage.success(data.message || "操作成功");
    ElMessage.error(data.message);
  });
}

function stopAdd() {
  ElMessageBox.confirm("确认停止添加任务？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "error"
  }).then(async () => {
    const data = await stopTaskApi();
    console.log("data", data);
    if (data.result) return ElMessage.success(data.message || "操作成功");
    ElMessage.error(data.message);
  });
}

async function getDetail() {
  const data = await getTaskDetailApi();
  detailList.value = data.detailList || [];
}

async function getAccountData() {
  const data = await getAccountListApi({
    page: 1,
    size: 6,
    with_messages: true,
    type_list: "全部",
    group_list: "全部",
    state_list: "全部"
  });
  accountData.value = data.data || [];
}

getDetail();
getAccountData();

defineOptions({ name: "PersonComp" });
</script>

<style scoped lang="scss">
@import "../person/index";
</style>
